package com.lincoln.framework.factories;

import com.lincoln.framework.bean.AbstractProtocol;
import com.lincoln.framework.bean.ProtocolContext;
import com.lincoln.framework.exception.ExecuteException;
import com.lincoln.framework.exception.ExecuteParamWrongException;
import com.lincoln.framework.interfaces.BaseExecute;
import com.lincoln.framework.interfaces.BaseProtocol;
import com.lincoln.util.ByteUtil;
import com.lincoln.util.PayloadUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;

/**
 * 登陆协议
 * 协议结构默认[头..][1][0][payload.length][payload][crc][尾..]
 * payload结构[imei长度(4位),imei,deviceType长度(4位),deviceType,protocolType长度(4位),protocolType,width长度(4位),width,height长度(4位),height]
 */
@Slf4j
public class DefaultLoginExecute extends BaseExecute {
    public static byte[] ServerCmd = {0};
    public static byte[] ClientCmd = {0};

    @Override
    public byte[] getServerCmd() {
        return ServerCmd;
    }

    @Override
    public byte[] getClientCmd() {
        return ClientCmd;
    }

    @Override
    public Logger getLogger() {
        return log;
    }

    @Override
    public boolean execute(BaseProtocol baseProtocol) throws ExecuteException {
        AbstractProtocol protocol = (AbstractProtocol) baseProtocol;
        // 取出imei号
        byte[] payload = protocol.getPayload();

        byte[][] params = PayloadUtil.resolvePayload(payload);

        if (params.length != 2) {
            throw new ExecuteParamWrongException();
        }
        int deviceType = ByteUtil.byte2int(params[0]);
        int protocolType = ByteUtil.byte2int(params[1]);
        ProtocolContext.getDevice().setDeviceType(deviceType);
        ProtocolContext.getDevice().setProtocolType(protocolType);

        log.info("ClientId:[" + ProtocolContext.getDevice().getClientId() + "],deviceType=[" + deviceType + "],protocolType=[" + protocolType + "],连接成功");
        ProtocolContext.getDevice().sendMsg(new AbstractProtocol(new byte[]{0}, PayloadUtil.generatePayload(ByteUtil.int2byte(1))));
        return true;
    }
}
